﻿/*
* YanSelect 选择插件
* Copyright 2011, 刘玉宏
* 2011-05-10 v1.0	编写
*/
(function ($) {
    $.fn.YanSelect = function (options) {
        var defaults = {
            secrhindex: [0, 1, 2],
            valueindex: 1,
            textindex: 2,
            isPage:true,
            pagelen: 10,
            isMulSel: false,
            iscanedit:false,
            dataobj: null,
            width: "500px",
            height: "400px",
            afterSelect: $.noop
            

        };
        var sel = 0;
        var options = $.extend(defaults, options);
        this.each(function () {
            var txt = $(this);
            txt.attr("autocomplete", "off");
            var tab = options.dataobj.clone().css({ "width": options.width, "background-color": "aliceblue" }).addClass("table table-striped table-bordered table-condensed table-hover");
            var tablediv = jQuery("<div>", { "class": "YanTabDiv well" }).append(tab.show()).hide()
            $("body").append(tablediv);
            
            if (!options.iscanedit) {
                txt.attr("onfocus", "this.blur()");
                $("thead", tab).prepend("<tr><th style='text-align:center' colspan='3'><div class='input-prepend' style=' margin-bottom: 0px;'><span class='add-on' style='width: 16px;' ><i class='icon-search'></i></span><input class='searinput' type='text' placeholder='搜索关键字' > </div></th></tr>");
            }
            //选择值
            $("tbody tr", tablediv).click(function (e) {
                e.stopPropagation();
                e.preventDefault();
                setvalue($(this));
            })

            //txt事件
            var searchinput = $(".searinput", tab);
            txt.click(function (e) {
                $(".YanTabDiv").hide();
                var txtoffset = $(this).offset();
                var txth = $(this).outerHeight(true);
                tablediv.css({ "top": txtoffset.top + txth, "left": txtoffset.left }).show();
                $(".searinput", tablediv).focus();

                getdata(txt);
            })
            txt.add(searchinput).keyup(function (e) {
                if (e.keyCode == 13) {//enter
                    e.preventDefault();
                    $("tbody tr", tablediv).each(function () {
                        if ($(this).hasClass("success")) {
                            setvalue($(this));
                            $("tbody tr", tablediv).removeClass("success")
                        }
                    })
                } else if (e.keyCode == 37) {//left
                } else if (e.keyCode == 38) {//up
                    if (sel > 0) {
                        sel--;
                        $("tbody tr", tablediv).removeClass("success").eq(sel).addClass("success");
                    }
                } else if (e.keyCode == 39) {//right
                } else if (e.keyCode == 40) {//down
                    //计算向下键能移动的距离
                    var count = options.pagelen > $("tbody tr[yanissel='Y']", tablediv).length ? $("tbody tr[yanissel='Y']", tablediv).length : options.pagelen;
                    if (sel < count) {
                        $("tbody tr", tablediv).removeClass("success").eq(sel).addClass("success");
                        sel++;
                    }
                } else {
                    sel = 0;
                    tablediv.show();
                    if (!options.iscanedit) {
                        getdata(searchinput);
                    }
                    else {
                        getdata(txt);
                    }
                }
            });
            if (options.isMulSel) {
                txt.blur(function () {
                    var realvalue = "";
                    txt.val(txt.val().substr(0, txt.val().lastIndexOf(",") + 1))
                    var arr = txt.val().substr(0, txt.val().length - 1).split(',');
                    for (var i = 0; i < arr.length; i++) {
                        $("tbody tr", tablediv).each(function () {
                            if ($(this).find('td').eq(options.textindex).text() == arr[i]) {
                                realvalue = realvalue + $(this).find('td').eq(options.valueindex).text() + ",";
                            }
                        });
                    }
                    txt.attr("realvalue", realvalue);
                });
            }
            var getdata = function (domint) {
                var text = domint.val();
                if (text != "") {
                    $("tbody tr", tablediv).each(function () {
                        var trtext = "";
                        var tr = $(this);
                        $.each(options.secrhindex, function (i, n) {
                            trtext = trtext + $.trim(tr.find('td').eq(n).text());
                        });
                        if (trtext.indexOf(text) >= 0) {
                            tr.show().attr("yanissel", "Y");
                        }
                        else {
                            tr.hide().attr("yanissel", "N");
                        }
                    })
                }
                else {
                    $("tbody tr", tablediv).attr("yanissel", "Y").show();
                }
                //如果不分页，则设定高度
                if (options.isPage) {
                    TableHelp.page(tab);
                } else {
                    tablediv.css({ "max-height": options.height, "overflow-y": "auto" });

                }
                $("tbody tr", tablediv).removeClass("success");
            }

            var setvalue = function (jdom) {
                var text = $.trim(jdom.find('td').eq(options.textindex).text());
                var value = $.trim(jdom.find('td').eq(options.valueindex).text());
                if (options.isMulSel) {
                    txt.val(txt.val().substr(0, txt.val().lastIndexOf(",") + 1) + text + ",");
                }
                else {
                    txt.val(text).attr("realvalue", value);
                    tablediv.hide();

                }
                txt.trigger("blur").trigger("change").next('input:hidden').val(value).trigger("change");
                //回调
                if ($.isFunction(options.afterSelect)) {
                    options.afterSelect.call(this, jdom);
                }
            }
            $("body").click(function (event) {
                var eventsrc =  event.srcElement || event.target;
                if (eventsrc) {
                    if (!tablediv[0].contains(eventsrc) && !txt[0].contains(eventsrc)) {
                        tablediv.hide();
                    }
                    sel = 0;
                }
            });
        });

        var TableHelp = {
            //判断任务是否有包含关系
            page: function (tab) {
                //添加分页
                var pagelen = Math.ceil($("tbody tr[yanissel='Y']", tab).length / options.pagelen);
                var pagestr = "<tfoot><tr ><td style='text-align: center;' colspan=" + $("th", tab).length + "><div class='pagination' style='margin:0px' ><ul><li class='previous disabled'><a href='#'>«</a></li>";
                if (pagelen === 0) {
                    pagestr = pagestr + "<li ><a href='#'>暂无数据</a></li>";
                }
                else {
                    for (var i = 1; i < pagelen + 1; i++) {
                        pagestr = pagestr + "<li class='" + (i === 1 ? 'page active' : 'page') + "' ><a href='#'>" + i + "</a></li>";
                    }
                }
                pagestr = pagestr + "<li class='next'><a href='#'>»</a></li></ul></div></td></tr></tfoot>";
                tab.find("tfoot").remove().end().append(pagestr);
                //添加分页

                //默认长度
                $("tbody tr", tab).slice(options.pagelen).hide();

                //绑定事件(页数)

                $("li", tab).click(function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var pageindex = 1;
                    //当前页
                    if ($(this).hasClass("page")) {
                        pageindex = $(this).text();
                    }
                    //上一页
                    if ($(this).hasClass("previous")) {
                        pageindex = $(".active", tab).text() - 1;
                    }
                    //下一页
                    if ($(this).hasClass("next")) {
                        pageindex = $(".active", tab).text() * 1 + 1
                    }
                    if (pageindex > 0 && pageindex <= pagelen) {
                        TableHelp.gopage(tab, pageindex);
                        $("li", tab).removeClass("disabled active");
                        $("li", tab).eq(pageindex).addClass("disabled active");
                    }
                })
            },
            gopage: function (tab, pageindex) {

                $("tbody tr", tab).slice(0, (pageindex - 1) * options.pagelen).each(function () {
                    if ($(this).attr("yanissel") === 'Y') {
                        $(this).hide();
                    }
                });
                $("tbody tr", tab).slice((pageindex - 1) * options.pagelen, pageindex * options.pagelen).each(function () {
                    if ($(this).attr("yanissel") === 'Y') {
                        $(this).show();
                    }
                })
                $("tbody tr", tab).slice(pageindex * options.pagelen).each(function () {
                    if ($(this).attr("yanissel") === 'Y') {
                        $(this).hide();
                    }
                })

            }
        };
    };
})(jQuery);